<!-- 角色数据展示页面 -->
<template>
  <div class="table">
    <el-table
      ref="roleTable"
      v-loading="isLoading"
      class="roleTable"
      :data="roleData"
      height="550"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        align="center"
        type="selection"
        width="49"
      />
      <el-table-column
        align="center"
        prop="id"
        label="序号"
        width="94"
      >
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template></el-table-column>
      <el-table-column
        align="center"
        prop="name"
        label="角色"
        width="125"
      />
      <el-table-column
        align="center"
        prop="code"
        label="角色编号"
        width="120"
      />
      <el-table-column
        align="center"
        prop="remark"
        label="角色备注"
        width="120"
      />
      <el-table-column
        align="center"
        prop="companyDTO.name"
        label="所属公司"
        width="120"
      />
      <el-table-column
        align="center"
        prop="organizationDTO.name"
        label="所属机构"
        width="120"
      />
      <el-table-column
        align="center"
        prop="status"
        label="启用"
        width="92"
      >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 1" type="success" size="mini">启用</el-tag>
          <el-tag v-else type="danger" size="mini">停用</el-tag>
        </template></el-table-column>
      <el-table-column
        align="center"
        label="操作"
        width="299"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            @click="copyRole(scope.$index, scope.row)"
          >复制</el-button>
          <el-button
            id="btnEdit1"
            size="mini"
            @click="editRole(scope.$index, scope.row)"
          >编辑</el-button>
          <el-button
            id="btnDel1"
            size="mini"
            type="danger"
            @click="deleteRole(scope.$index, scope.row)"
          >删除</el-button>
          <el-button
            size="mini"
            type="warning"
            @click="viewPermission(scope.$index, scope.row)"
          >查看权限</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :current-page.sync="paginationData.pageCount"
      :page-size="paginationData.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="paginationData.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script>
import {
  commonQuery,
  remove
} from '@/api/right/role'

export default {
  name: 'Table',
  data() {
    return {
      // 角色信息
      roleData: [],
      // 当前页选中的角色信息
      currentRoleDataSelection: [],
      // 被选中的角色信息表 用于跨页
      roleDataSelectionForm: [],
      // 被选中的角色信息
      roleDataSelection: [],
      // 分页信息
      paginationData: {
        // 当前页面序号，默认为1
        pageCount: 1,
        // 每页数据数
        pageSize: 10,
        // 总共数据数
        total: 0,
        // 总页面数
        pages: null
      },
      // role参数
      roleQuery: {
        // 页号
        pageNum: 1,
        // 页大小
        pageSize: 10,
        // 角色名称
        name: ''
      },
      // 是否处于加载状态
      isLoading: false
    }
  },
  mounted() {
    // 初始化角色数据
    this.getRole()
    // 增删改查后调用，更新角色数据
    this.$on('getRole', function() {
      this.getRole(this.userQuery)
    })
    // 查询是调用，搜索对应得用户数据
    this.$on('searchRole', name => {
      this.roleQuery.name = name
      this.getRole()
    })
  },
  methods: {
    /**
     * 更改被选中数据的数组
     * @param {*} val 被选中的数据
     */
    handleSelectionChange(val) {
      // 更新选中的数据
      val.forEach(item => {
        if (!this.currentRoleDataSelection.includes(item)) {
          this.roleDataSelection.push(item)
        }
      })
      this.currentRoleDataSelection.forEach(item => {
        if (!val.includes(item)) {
          const index = this.roleDataSelection.findIndex(v => v === item)
          this.roleDataSelection.splice(index, 1)
        }
      })

      this.currentRoleDataSelection = val
    },
    /**
     * 获取角色信息
     */
    async getRole() {
      try {
        this.isLoading = true
        let res = await commonQuery(this.roleQuery)
        if (!res) {
          this.$message.error('角色信息获取失败')
          return
        }
        const { total, pageNum, pages, data } = res
        this.paginationData.pageNum = parseInt(pageNum)
        this.paginationData.total = parseInt(total)
        this.paginationData.pages = parseInt(pages)
        this.roleData = data

        // 若本页有数据被选中，则选中
        this.$nextTick(() => {
          if (this.roleDataSelectionForm[this.paginationData.pageCount - 1]) {
            const rows = this.roleDataSelectionForm[this.paginationData.pageCount - 1]
            rows.forEach(row => {
              this.roleData.map(item => {
                if (item.id === row.id) {
                  this.$refs.roleTable.toggleRowSelection(item, true)
                }
              })
            })
          }
        })
      } catch {
        this.$message.error('网络错误')
      } finally {
        this.isLoading = false
      }
    },
    /**
     * 复制角色
     * @param {*} index 角色序号
     * @param {*} row 角色数据
     */
    copyRole(index, row) {
      this.$emit('copyRole', row)
    },
    /**
     * 编辑角色
     * @param {*} index 角色序号
     * @param {*} row 角色数据
     */
    editRole(index, row) {
      this.$emit('editRole', row)
    },
    /**
     * 删除角色
     * @param {*} index 角色序号
     * @param {*} row 角色数据
     */
    deleteRole(index, row) {
      this.$confirm('确定要删除吗')
        .then(async() => {
          try {
            let res = await remove({ id: row.id, version: row.version })
            if (res) {
              this.$message.success('删除成功')
              this.getRole()
            } else {
              this.$message.error('删除失败')
            }
          } catch {
            this.$message.error('网络错误')
          }
        })
        .catch(req => {})
    },
    /**
     * 查看权限
     * @param {*} index 角色序号
     * @param {*} row 角色数据
     */
    viewPermission(index, row) {
      this.$emit('viewPermission', row)
    },
    /**
     * 更改页面尺寸时重新获取数据
     * @param {*} val
     */
    handleSizeChange(val) {
      this.paginationData.pageSize = val
      this.roleQuery.pageSize = val
      this.roleDataSelectionForm = []
      this.roleDataSelection = []
      this.currentRoleDataSelection = []
      this.getRole()
    },
    /**
     * 当前页面发生变化时重新获取数据
     * @param {*} val
     */
    handleCurrentChange(val) {
      this.roleDataSelectionForm[this.roleQuery.pageNum - 1] = this.currentRoleDataSelection
      // 添加离去页的数据，防止遗漏
      this.roleDataSelection.push(...this.currentRoleDataSelection)
      // 删除到达页的数据，防止重复
      if (this.roleDataSelectionForm[val - 1]) {
        this.roleDataSelectionForm[val - 1].forEach(item => {
          const index = this.roleDataSelection.findIndex(v => v === item)
          this.roleDataSelection.splice(index, 1)
        })
      }

      this.paginationData.pageCount = val
      this.roleQuery.pageNum = val
      this.getRole()
    }
  }
}
</script>

<style lang="scss" scoped>
.table {
  width: 89.1%;
  .roleTable{
    margin-top: 20px;
    margin-bottom: 10px;
  }
}
</style>
